﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Data.SqlClient;

namespace JFLERP.IQ
{
    public partial class SAPMaterialMasterPirceList : DevExpress.XtraEditors.XtraForm, IMdiChildActions
    {


        public SAP_MM_P AccessType { get; set; }



        public SAPMaterialMasterPirceList()
        {
            InitializeComponent();


        }

        #region IMdiChildActions 成员

        public void Save()
        {

        }

        public void New()
        {

        }

        public void Delete()
        {

        }

        public void Print()
        {

        }

        public void SelectAll()
        {

        }

        public void Find()
        {

        }

        public void Export()
        {

        }

        #endregion



        private void GetDataFromSystem(SAP_MM_P StepNumber)
        {

            try
            {

                string sql = "EXEC sp_SAP_GetPriceList '" + CFunctionUtility.CFListToStringWithoutComma(txt_MaterialNumber.Text.Trim(), ',') + "','-'";

                if (txt_BIReportName.Text != "")
                {
                    sql = "EXEC sp_SAP_GetPriceList '-','" + txt_BIReportName.Text + "'";
                }

                System.Data.DataTable dt = DbHelperSQL.Query(sql).Tables[0];
                this.gdc_MpsMain.DataSource = dt;
                this.xtraTabControl1.SelectedTabPageIndex = 0;

                if (dt.Rows.Count > 0)
                {
                    txtFileName.Text = dt.Rows[0]["BIName"].ToString();
                    this.Text = "SAP 物料主数据价格跟踪" + dt.Rows.Count.ToString();
                }
      
                this.bandedGridColumn_Delay_CG.BestFit();
                this.bandedGridColumn_Delay_GY.BestFit();
                

                InitGrand();
            }
            catch (Exception ex)
            {


            }

        }

        private void InitGrand()
        {
            //foreach (DevExpress.XtraGrid.Views.BandedGrid.GridBand item in this.gdv_MpsMain.Bands)
            //{
            //    if (item.Name == "gridBand_Procurement" || item.Name == gridBand_basic.Name || item.Name == gridBand_PEInfo.Name)
            //    {
            //        item.Visible = true;
            //    }
            //    else
            //    {
            //        item.Visible = chk_OnlyForPOView.Checked;
            //    }
            //}
        }


        private void btnSearch_Click(object sender, EventArgs e)
        {

            this.GetDataFromSystem(SAP_MM_P.ALL);

        }  

        public enum SAP_MM_P
        {
            NONE,
            PO,
            PE,
            ALL,
            PL,
            GC,
            SAPUpload,
            FIN,
            SYCHN,
            V1,
            V2,
            V3
        }


        private void gdv_MpsMain_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }
        bool boolCopy = false;
        private void gdv_MpsMain_KeyUp(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void frmStatusMonitor_JobMatReq_Load(object sender, EventArgs e)
        {
            CFunctionUtility.InitGridViewSetColumnReadOnly(this.gdv_MpsMain, true);
            txtUserName.Text = Commoner.UseName.Trim();
            this.btn_SAPupload.Enabled = false;
            this.txtUpload_V1.Enabled = false;
            this.txtUpload_V2.Enabled = false;
            this.txtUpload_V3.Enabled = false;
            this.txtUpload_PL.Enabled = false;

            this.bandedGridColumn_del.Visible = true;
            this.bandedGridColumn_del.OptionsColumn.AllowEdit = true;
 
            if ( CFunctionUtility.IsSysAdmin())
            {
                this.btn_SAPupload.Enabled = true;
                this.txtUpload_V1.Enabled = true;
                this.txtUpload_V2.Enabled = true;
                this.txtUpload_PL.Enabled = true;
                this.txtUpload_V3.Enabled = true;
              
                 

            }
            else
            {
                
                
            }
            if (AccessType == SAP_MM_P.V2) { this.txtUpload_V2.Enabled = true;   }
            if (AccessType == SAP_MM_P.V1)
            {
                this.txtUpload_V1.Enabled = true;
                
            }
            if (AccessType == SAP_MM_P.PO)
            {
                this.txtUpload_V3.Enabled = true;
                if (CFunctionUtility.IsSysAdmin())
                {
                    

                }
                else
                {
                }
                
            }
           
        


            foreach (DevExpress.XtraGrid.Views.BandedGrid.BandedGridColumn item in this.gdv_MpsMain.Columns)
            {
                item.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            }

            foreach (DevExpress.XtraGrid.Views.BandedGrid.GridBand item in this.gdv_MpsMain.Bands)
            {
                item.AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            }



            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "PO_PIR_Status", "Y", Color.YellowGreen,false);
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "PO_PIR_Status", "N", Color.Yellow,false );
            //
            CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "FROM_MST", "Y", Color.Aqua, false);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "ActiveStatus", "X", Color.Yellow);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "EditStatus", "Y", Color.Yellow);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "IsMissPOview", "Y", Color.Red);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "NeedToSynch", "Y", Color.Pink);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "T4SStatus", "-", Color.Aqua);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "SendToPOFlag", "-", Color.Tomato, false);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "ProdOrderStatus", "OPEN", Color.Purple, false);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "BOMAndRoutingStatus", "Y", Color.YellowGreen, false);
            //CFunctionUtility.InitGridViewFormatStyle(this.gdv_MpsMain, "SpecialFlag", "Y", Color.Yellow, false);
            //
            if (!CFunctionUtility.IsSysAdmin())
            {
                this.导出汇总ToolStripMenuItem.Visible = false;
                 

            }
            ///不是管理员不显示
            if (!CFunctionUtility.IsSysAdmin())
            {
                this.txtUserName.Visible = false;
                this.txt_var.Visible = false;
            }
            else
            {
                this.txtUserName.Visible = true;
                this.txt_var.Visible = true;
            }

            this.InitWCGLookupList();
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            SaveFileDialog opf = new SaveFileDialog();
            opf.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\1 Data Download\\";
            opf.FileName = txtFileName.Text;
            if (opf.ShowDialog() == DialogResult.OK)
            {
                string fileName = opf.FileName;
                if (!opf.FileName.EndsWith("xlsx"))
                {
                    fileName = fileName + ".xlsx";
                }
                this.gdv_MpsMain.OptionsPrint.AutoWidth = false;
                this.gdv_MpsMain.ExportToXlsx(fileName, new DevExpress.XtraPrinting.XlsxExportOptions() { SheetName = "Sheet1" });
            }
        }
        List<SAPItemQueryInfo> LstSAPUploadList = new List<SAPItemQueryInfo>();
        private void txtWorkOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (!CFunctionUtility.IsSysAdmin() && true)
            {
                frmPVSelect newform = new frmPVSelect();
                newform.TFormName = "工作令选择";
                newform.TstrTable = "cv_SO_WorkOrderMaster";
                newform.TSetMulRows = false;
                newform.TstrTitle = "WorkOrderDesc,工作令;ItemCode,物料号;ItemDrawingNumber,物料图号;ItemName,物料名称;ItemDescription,物料描述;OrderNumber,销售订单;OrderLine,订单行";
                newform.TSelFields = "WorkOrderDesc,工作令;ItemCode,物料号;ItemDrawingNumber,物料图号;ItemName,物料名称;ItemDescription,物料描述;OrderNumber,销售订单;OrderLine,订单行;Qty,数量;ItemCategory,物料性质";
                newform.TSpecialWhere = " And ItemCategory='M'";
                newform.TOrderBY = " Order by WorkOrderDesc";
                newform.TShowDetail = true;
                newform.ShowDialog();
                if (newform.TDataRow != null)
                {
                    string rtn = string.Empty;
                    foreach (DataRow row in newform.TDataRows)
                    {
                        if (rtn == "")
                        {
                            rtn = row["WorkOrderDesc"].ToString().Trim();
                        }
                        else
                        {
                            rtn += "," + row["WorkOrderDesc"].ToString().Trim();
                        }
                    }
                    //txt_ItemCode.Text = CommonHandle.TransRange(rtn);
                }
            }
            else
            {
                StringBuilder sb_WorkOrder = new StringBuilder();
                LstSAPUploadList.Clear();

                OpenFileDialog opf = new OpenFileDialog();
                if (opf.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                txtPath.Text = opf.FileName;

                try
                {
                    if (!string.IsNullOrEmpty(txtPath.Text))
                    {
                        System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                        List<string> LstSQL = new List<string>();
                        for (int i = 0; i < dt_excel.Rows.Count; i++)
                        {
                            string strItemCode = "";
                            string XH = "";
                            strItemCode = dt_excel.Rows[i][0].ToString();
                            //XH = dt_excel.Rows[i][0].ToString(); 
                            if (!string.IsNullOrEmpty(strItemCode))
                            {

                                sb_WorkOrder.AppendFormat("{0},", strItemCode);
                            }
                        }



                    }
                }
                catch (Exception ex)
                {

                }
                finally
                {
                    if (sb_WorkOrder.Length > 1)
                    {
                        //  txtWorkOrder.Text = sb_WorkOrder.Remove(sb_WorkOrder.Length - 1, 1).ToString();
                    }
                }
            }
        }

        private void gdv_MpsMain_CustomDrawRowIndicator_1(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MpsMain);
        }

        private void gdv_MpsMain_KeyDown_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyDown(e, out boolCopy);
        }

        private void gdv_MpsMain_KeyUp_1(object sender, KeyEventArgs e)
        {
            CFunctionUtility.InitGridViewForCopy_KeyUp(e, this.gdv_MpsMain, out boolCopy);
        }

        private void gdv_MpsMain_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e)
        {
            DataRow dr = gdv_MpsMain.GetDataRow(e.RowHandle);
            // if (e.Column.FieldName == "ProductionQty")
            //{
            //    if (decimal.Parse(dr["OrderQty"].ToString()) == decimal.Parse(dr["ProductionQty"].ToString()))
            //    {
            //        e.Appearance.BackColor = Color.YellowGreen;
            //    }
            //}
            // if (e.Column.FieldName == "DeliveriedQty")
            // {
            //     if (decimal.Parse(dr["OrderQty"].ToString()) == decimal.Parse(dr["DeliveriedQty"].ToString()))
            //     {
            //         e.Appearance.BackColor = Color.YellowGreen;
            //     }
            // }
        }

        private void chkIsShowOperator_CheckedChanged(object sender, EventArgs e)
        {

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in gdv_MpsMain.Columns)
            {

            }

        }

        

        private void DOUploadMaterial_PO_PIR(string UploadType)
        {
            StringBuilder sb_WorkOrder = new StringBuilder();
            LstSAPUploadList.Clear();
            try
            {
                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 0; i < dt_excel.Rows.Count; i++)
                    {

                        string _Material_Number = dt_excel.Rows[i][0].ToString().Trim();
                        string _PR_Date = dt_excel.Rows[i][3].ToString();
                        string _DrawingDate = dt_excel.Rows[i][4].ToString();
                        string _TargetDate = dt_excel.Rows[i][5].ToString();
                        string _PurchasingGroup = dt_excel.Rows[i][7].ToString();
                        string _LeadTime = dt_excel.Rows[i][8].ToString();
                        string _MOQ = dt_excel.Rows[i][9].ToString();
                        string _NetPrice = dt_excel.Rows[i][10].ToString();
                        string _Currency = dt_excel.Rows[i][11].ToString();
                        string _PR_Remark = dt_excel.Rows[i][12].ToString();
                        if (!string.IsNullOrEmpty(_Material_Number))
                        {
                            LstSAPUploadList.Add(new SAPItemQueryInfo
                            {
                                Material_Number = _Material_Number,
                                PIR_User = Commoner.UseName.Trim(),
                                PurchasingGroup = _PurchasingGroup.Trim(),
                                Upload_Type = UploadType.Trim(),
                                TargetDate = _TargetDate,
                                DrawingDate = _DrawingDate,
                                NetPrice = _NetPrice,
                                Currency = _Currency,
                                Minimum_Lot_Size = _MOQ,
                                Planned_Delivery_Days = _LeadTime,
                                PR_Date = _PR_Date,
                                PIR_Remark = _PR_Remark
                            });
                        }
                    }
                }
                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstSAPUploadList.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();

                    foreach (SAPItemQueryInfo item in LstSAPUploadList)
                    {
                        if (!string.IsNullOrEmpty(item.Material_Number))
                        {
                            StringBuilder sbSql_ex = new StringBuilder();
                            sbSql_ex.Append("EXEC	sp_SAP_MassUploadPrice ");
                            sbSql_ex.AppendFormat("		@Material = N'{0}', ", item.Material_Number);
                            sbSql_ex.AppendFormat("		@PR_Date = N'{0}', ", item.PR_Date);
                            sbSql_ex.AppendFormat("		@DrawingDate = N'{0}', ", item.DrawingDate);
                            sbSql_ex.AppendFormat("		@TagetDate = N'{0}', ", item.TargetDate);
                            sbSql_ex.AppendFormat("		@NetPrice = N'{0}', ", item.NetPrice);
                            sbSql_ex.AppendFormat("		@User = N'{0}', ", item.PIR_User);
                            sbSql_ex.AppendFormat("		@PurchasingGroup = N'{0}', ", item.PurchasingGroup);
                            sbSql_ex.AppendFormat("		@MOQ = N'{0}', ", item.Minimum_Lot_Size);
                            sbSql_ex.AppendFormat("		@LT = N'{0}', ", item.Planned_Delivery_Days);
                            sbSql_ex.AppendFormat("		@Currency = N'{0}', ", item.Currency);
                            sbSql_ex.AppendFormat("		@PIR_Remark = N'{0}', ", item.PIR_Remark);
                            sbSql_ex.AppendFormat("		@Upload_Type = N'{0}' ", UploadType);
                            LstSQL.Add(sbSql_ex.ToString());
                            sbm.AppendFormat("{0},", item.Material_Number);
                        }
                    }

                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }
                if (MessageBox.Show("确定要【采购询价信息】进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }
                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }

        
        
 

      

      

        private void repositoryItemSpinEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

        }

        private void repositoryItemButtonEdit_Delete_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            DataRow dr = this.gdv_MpsMain.GetFocusedDataRow();
            if (dr != null)
            {
                frmPVSelect newform = new frmPVSelect();
                newform.TFormName = "采购价格日志";
                newform.TstrTable = "SAP_PIR_Detail"; // "cv_YearMonth"; 
                newform.TSelFields = "Material,Material;PO_User,操作人; PO_DrawingDate, 图纸日期; PO_TargetDate,目标日期;PO_Price,询价;PO_MOQ,MOQ;PO_LT,采购周期;PO_Currency,币种;PO_PurchasingGroup,采购组;CreateDate,提交日期";
                newform.TOrderBY = " Order  by CreateDate desc";
                newform.TSpecialWhere = "  AND Material='" + dr["Material_Number"].ToString() + "'"; // " And Year*100+Month>=2014*100+11 ";
                newform.Width = 650;
                newform.Height = 700;
                newform.ShowDialog();
            }
             
        }

        private void txtFileName_TextChanged(object sender, EventArgs e)
        {

        }

    

     

        private void btn_ExtendFinished_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            
        }

        /// <summary>
        /// 获得模板SN
        /// </summary>
        /// <param name="typeName"></param>
        /// <returns></returns>
        public string GetSNByType(string typeName)
        {
            StringBuilder sbSql_sn = new StringBuilder();
            sbSql_sn.Append("SELECT top 1   z.SN  FROM SAP_Template_Version z ");
            sbSql_sn.AppendFormat("WHERE z.TypeName='{0}' ", typeName);
            return DbHelperSQL.Query(sbSql_sn.ToString()).Tables[0].Rows[0]["SN"].ToString();
        }

        private void InitWCGLookupList()
        {

            StringBuilder sbSql = new StringBuilder();
            sbSql.Append("SELECT sph.[GROUP], sph.Main_Group, sph.Subgroup, sph.Prod_Hierarchy, ");
            sbSql.Append("       sph.Prod_Hierarchy_Code ");
            sbSql.Append("  FROM SAP_ProductHierarchy sph ");
            sbSql.Append("ORDER BY  sph.Prod_Hierarchy_Code ");

            DataSet dstemp = DbHelperSQL.Query(sbSql.ToString());

            if (dstemp != null && dstemp.Tables.Count > 0)
            {


                this.repositoryItemLookUpEdit_PrdHrchy.DataSource = dstemp.Tables[0];


                this.repositoryItemLookUpEdit_PrdHrchy.DisplayMember = "Prod_Hierarchy";
                this.repositoryItemLookUpEdit_PrdHrchy.ValueMember = "Prod_Hierarchy_Code";


            }

        }

        private void repositoryItemButtonEdit_ProHrchySave_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
           
        }

   

        private void 导入ViewResultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            DOUploadMaterial_ViewStatus();
        }


        private void DOUploadMaterial_ViewStatus()
        {
            StringBuilder sb_WorkOrder = new StringBuilder();

            List<SAP_ViewStatus> LstView = new List<SAP_ViewStatus>();

            try
            {

                if (!string.IsNullOrEmpty(txtPath.Text))
                {
                    System.Data.DataTable dt_excel = CFunctionUtility.LoadDataFromExcelForDataTable(txtPath.Text);

                    List<string> LstSQL = new List<string>();
                    for (int i = 0; i < dt_excel.Rows.Count; i++)
                    {

                        string _Material = dt_excel.Rows[i][0].ToString();
                        string _BASIC_VIEW = dt_excel.Rows[i][1].ToString();
                        string _SALES = dt_excel.Rows[i][2].ToString();
                        string _PURCHASING = dt_excel.Rows[i][3].ToString();
                        string _WORK_SCHEDULING = dt_excel.Rows[i][4].ToString();
                        string _QUALITY_MANAGEMENT = dt_excel.Rows[i][5].ToString();
                        string _ACCOUNTING = dt_excel.Rows[i][6].ToString();
                        string _COSTING = dt_excel.Rows[i][7].ToString();
                        string _MRP = dt_excel.Rows[i][8].ToString();
                        string _PLANT_STORAGE_LOC = dt_excel.Rows[i][9].ToString();
                        string _PROCUREMENT_TYPE = dt_excel.Rows[i][10].ToString();
                        string _MATERIAL_PLANT_STATUS = dt_excel.Rows[i][11].ToString();
                        string _COST_PRICE = dt_excel.Rows[i][12].ToString();
                        string _Crcy = dt_excel.Rows[i][13].ToString();

                        string _IN_HOUSE_TIME = dt_excel.Rows[i][14].ToString();
                        string _PLAN_DEL_TIME = dt_excel.Rows[i][15].ToString();
                        string _MRP_TYPE = dt_excel.Rows[i][16].ToString();
                        string _STRATEGY_GROUP = dt_excel.Rows[i][17].ToString();
                        string _BOM_EXIT = dt_excel.Rows[i][18].ToString();
                        
                        string _PRODUCT_HIERARCHY_S = dt_excel.Rows[i][19].ToString();
                        string _PRODUCT_HIERARCHY = dt_excel.Rows[i][20].ToString();
                        string _ENName = dt_excel.Rows[i][21].ToString();
                        string _CNName = dt_excel.Rows[i][22].ToString();


                        if (!string.IsNullOrEmpty(_Material))
                        {
                            LstView.Add(new SAP_ViewStatus
                            {
                                ACCOUNTING = _ACCOUNTING,
                                BASIC_VIEW = _BASIC_VIEW,
                                COST_PRICE = _COST_PRICE,
                                COSTING = _COSTING,
                                Crcy = _Crcy,
                                Material = _Material,
                                MATERIAL_PLANT_STATUS = _MATERIAL_PLANT_STATUS,
                                MRP = _MRP,
                                PLANT_STORAGE_LOC = _PLANT_STORAGE_LOC,
                                PROCUREMENT_TYPE = _PROCUREMENT_TYPE,
                                PURCHASING = _PURCHASING,
                                QUALITY_MANAGEMENT = _QUALITY_MANAGEMENT,
                                SALES = _SALES,
                                WORK_SCHEDULING = _WORK_SCHEDULING,
                                BOM_EXIT = _BOM_EXIT,
                                IN_HOUSE_TIME = _IN_HOUSE_TIME,
                                MRP_TYPE = _MRP_TYPE,
                                PLAN_DEL_TIME = _PLAN_DEL_TIME,
                                PRODUCT_HIERARCHY = _PRODUCT_HIERARCHY,
                                ROUTING_EXIT = "",
                                STRATEGY_GROUP = _STRATEGY_GROUP,
                                _CNName = _CNName.Replace("'","''"),
                                _ENName = _ENName.Replace("'","''"),
                                PRODUCT_HIERARCHY_S = _PRODUCT_HIERARCHY_S

                            });
                        }
                    }
                }

                this.gdc_MpsMain.RefreshDataSource();
            }
            catch (Exception ex)
            {

            }
            finally
            {
                List<string> LstSQL = new List<string>();

                if (LstView.Count > 0)
                {
                    StringBuilder sbm = new StringBuilder();
                    foreach (SAP_ViewStatus item in LstView)
                    {
                        StringBuilder sbSql_v = new StringBuilder();
                        sbSql_v.Append("exec SP_Upload_SAPMaterialToMonitor_View  ");
                        sbSql_v.AppendFormat("@Material ='{0}', ", item.Material);
                        sbSql_v.AppendFormat("@BASIC_VIEW ='{0}', ", item.BASIC_VIEW);
                        sbSql_v.AppendFormat("@SALES ='{0}', ", item.SALES);
                        sbSql_v.AppendFormat("@PURCHASING ='{0}', ", item.PURCHASING);
                        sbSql_v.AppendFormat("@WORK_SCHEDULING ='{0}', ", item.WORK_SCHEDULING);
                        sbSql_v.AppendFormat("@QUALITY_MANAGEMENT  ='{0}', ", item.QUALITY_MANAGEMENT);
                        sbSql_v.AppendFormat("@ACCOUNTING ='{0}', ", item.ACCOUNTING);
                        sbSql_v.AppendFormat("@COSTING ='{0}', ", item.COSTING);
                        sbSql_v.AppendFormat("@MRP ='{0}', ", item.MRP);
                        sbSql_v.AppendFormat("@PLANT_STORAGE_LOC ='{0}', ", item.PLANT_STORAGE_LOC);
                        sbSql_v.AppendFormat("@PROCUREMENT_TYPE ='{0}', ", item.PROCUREMENT_TYPE);
                        sbSql_v.AppendFormat("@MATERIAL_PLANT_STATUS ='{0}', ", item.MATERIAL_PLANT_STATUS);
                        sbSql_v.AppendFormat("@COST_PRICE  ='{0}', ", item.COST_PRICE);
                        sbSql_v.AppendFormat("@Crcy ='{0}', ", item.Crcy);
                        sbSql_v.AppendFormat("@PRODUCT_HIERARCHY ='{0}', ", item.PRODUCT_HIERARCHY);
                        sbSql_v.AppendFormat("@IN_HOUSE_TIME ='{0}', ", item.IN_HOUSE_TIME);
                        sbSql_v.AppendFormat("@PLAN_DEL_TIME ='{0}', ", item.PLAN_DEL_TIME);
                        sbSql_v.AppendFormat("@MRP_TYPE ='{0}', ", item.MRP_TYPE);
                        sbSql_v.AppendFormat("@STRATEGY_GROUP ='{0}', ", item.STRATEGY_GROUP);
                        sbSql_v.AppendFormat("@BOM_EXIT ='{0}', ", item.BOM_EXIT);
                        sbSql_v.AppendFormat("@ROUTING_EXIT ='{0}', ", item.ROUTING_EXIT);
                        sbSql_v.AppendFormat("@V_ProdHierarchy_SALES ='{0}', ", item.PRODUCT_HIERARCHY_S);
                        sbSql_v.AppendFormat("@V_EN_NAME ='{0}', ", item._ENName);
                        sbSql_v.AppendFormat("@V_CN_NAME ='{0}' ", item._CNName);
                      
                        LstSQL.Add(string.Format(sbSql_v.ToString()));
                        sbm.AppendFormat("{0},", item.Material);
                    }
                    if (sbm.Length > 0)
                    {
                        sbm.Remove(sbm.Length - 1, 1);
                        txt_MaterialNumber.Text = sbm.ToString();
                    }
                }

                if (MessageBox.Show("确定要进行上传数据吗?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                }

                this.GetDataFromSystem(SAP_MM_P.ALL);
            }
        }

   

        private void btnChange_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(rch_MaterialList.Text);
            sb.Replace("\t\n", "|");
            sb.Replace("\n", "|");
            sb.Replace(" ", "");
            rch_MaterialList.Text = sb.ToString().Replace("|", ",");
            if (rch_MaterialList.Text.EndsWith(","))
            {
                rch_MaterialList.Text = rch_MaterialList.Text.Substring(0, sb.Length - 1);
            }
        }

        private void btnCopy_Click(object sender, EventArgs e)
        {
            txt_MaterialNumber.Text = rch_MaterialList.Text;
        }

      

      

        private void btnReverse_Click(object sender, EventArgs e)
        {
            StringBuilder sblst = new StringBuilder();
            foreach (string item in txt_MaterialNumber.Text.Split(','))
            {
                sblst.Append(item.Trim());
                sblst.AppendLine();
            }
            this.rch_MaterialList.Text = sblst.ToString();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.rch_MaterialList.Text = "";
        }

        private void chk_OnlyForPOView_CheckedChanged(object sender, EventArgs e)
        {
            InitGrand();
        }

      

        

      



        private void btnUpload_prodhrchy_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            if (!txtPath.Text.Contains(this.GetSNByType("GP"))) { MessageBox.Show("模板已经过期,数据无法上传!请找管理员获得新版模板!"); return; }
            else
            {
                
            }
        }


       
        private void btn_PCNNOUpload_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            if (!txtPath.Text.Contains(this.GetSNByType("PCN"))) { MessageBox.Show("模板已经过期,数据无法上传!请找管理员获得新版模板!"); return; }
            else
            {
                //DOUploadMaterial_GC_PCN_NO();
            }
        }

      

        
        

        

        
        private void txt_BIReportName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmPVSelect newform = new frmPVSelect();
            newform.TFormName = "BI Report List";
            newform.TstrTable = "SAP_BIReportName"; // "cv_YearMonth"; 
            newform.TSelFields = "BICode,代码;BIName,报表名称;RecordQty,记录数;Owner,归属人";
            newform.TOrderBY = " Order  by BIName";
            newform.TSpecialWhere = " and FunctionName='PIR'"; // " And Year*100+Month>=2014*100+11 ";
            newform.Width = 550;
            newform.Height = 700;

            newform.ShowDialog();

            if (newform.TDataRow != null)
            {

                txt_BIReportName.Text = newform.TDataRow["BICode"].ToString();

            }
        }

        private void txt_BIReportName_DoubleClick(object sender, EventArgs e)
        {
            txt_BIReportName.Text = "";
        }

        private void btn_TableToList_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            if ((this.gdc_MpsMain.DataSource as System.Data.DataTable) != null)
            {

                foreach (DataRow dr in (this.gdc_MpsMain.DataSource as System.Data.DataTable).Rows)
                {
                    sb.AppendFormat("{0}{1}", dr["Material_Number"].ToString(), System.Environment.NewLine);
                }
                rch_MaterialList.Text = "";
                rch_MaterialList.AppendText(sb.ToString());
            }
        }

        private void 导出到ExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.ExportToExcel(this.gdv_MonitorList, txt_BIReportName.Text);
        }


        private void ExportToExcel(DevExpress.XtraGrid.Views.Grid.GridView gdv, string strFileName)
        {
            SaveFileDialog sv = new SaveFileDialog();
            sv.Filter = "xlsx|xlsx";
            sv.FileName = strFileName + ".xlsx";
            if (sv.ShowDialog() == DialogResult.OK)
            {

                string fileName = sv.FileName;
                if (!fileName.EndsWith(".xls") && !fileName.EndsWith(".xlsx"))
                {
                    fileName = fileName + ".xlsx";
                }
                DevExpress.XtraGrid.Views.Grid.GridView gv = new DevExpress.XtraGrid.Views.Grid.GridView();
                gv = gdv;
                gv.OptionsPrint.AutoWidth = false;
                gv.ExportToXlsx(fileName, new DevExpress.XtraPrinting.XlsxExportOptions() { SheetName = "Sheet1" });
                MessageBox.Show("导出完毕", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void simpleButton3_Click_1(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            if ((this.gdc_MasterDataMonitor.DataSource as System.Data.DataTable) != null)
            {
                foreach (DataRow dr in (this.gdc_MasterDataMonitor.DataSource as System.Data.DataTable).Rows)
                {
                    sb.AppendFormat("{0}{1}", dr["Material"].ToString(), System.Environment.NewLine);
                }
                rch_MaterialList.Text = "";
                rch_MaterialList.AppendText(sb.ToString());
            }
        }

        private void gdv_MonitorList_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            CFunctionUtility.DevCustomDrawRowIndicator(e, this.gdv_MonitorList);
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfPriceProgress("DELETE_MARC", "确定删除MARC吗?");
        }

        private void rch_MaterialList_DoubleClick(object sender, EventArgs e)
        {
            rch_MaterialList.SelectAll();
        }

      

        private void txtUpload_V1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;

            DOUploadMaterial_PO_PIR("V1");

        }

        private void txtUpload_V2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            txtPath.Text = opf.FileName;
            DOUploadMaterial_PO_PIR("V2");
        }

        private void txtUpload_V3_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog opf = new OpenFileDialog();
            if (opf.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            this.DOUploadMaterial_PO_PIR("V3");
        }

        private void btn_TaskFlag_Click(object sender, EventArgs e)
        {
            UploadSAPStatusOfPriceProgress("V0", "确定要分配任务给相关Sourcing吗?");
        }
        private void UploadSAPStatusOfPriceProgress(string uploadType, string Msg)
        {

            if (string.IsNullOrEmpty(txt_MaterialNumber.Text))
            {
                MessageBox.Show("请选择你需物料", "", MessageBoxButtons.OK);
                return;
            }

            List<string> LstSQL = new List<string>();

            foreach (string itemcode in txt_MaterialNumber.Text.Split(','))
            {
                string sbSql_v = string.Format(" exec sp_Upload_SAP_MaterialPriceStatus @MaterialNumber='{0}',@UploadType='{1}',@CreateUser='{2}',@Values='{3}' ", itemcode.ToUpper().Trim(), uploadType, txtUserName.Text.Trim(), txt_var.Text.Trim());
                LstSQL.Add(string.Format(sbSql_v.ToString()));
            }
            if (MessageBox.Show(string.Format("确定要进度完成【{0}】?", Msg), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                if (LstSQL.Count > 0)
                {
                    DbHelperSQL.ExecuteSqlTran(LstSQL);
                    MessageBox.Show("上传完毕，请核实!");
                    this.GetDataFromSystem(SAP_MM_P.ALL);
                    this.xtraTabControl1.SelectedTabPageIndex = 0;
                }
                else
                {
                    MessageBox.Show("没有数据要进行登记");
                }
            }

        }

      


    }

 
}